package com.burst.reptile.modular.zp.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burst.reptile.common.utils.DateUtil;
import com.burst.reptile.common.utils.NumberUtils;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.common.utils.UserAgentUtils;
import com.burst.reptile.framework.aspectj.lang.annotation.ReadContent;
import com.burst.reptile.framework.constant.ConstantFactory;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.framework.web.controller.BaseController;
import com.burst.reptile.modular.system.entity.SysUser;
import com.burst.reptile.modular.system.service.ISysUserService;
import com.burst.reptile.modular.web.entity.ZpBanner;
import com.burst.reptile.modular.web.entity.ZpWebinfo;
import com.burst.reptile.modular.web.service.IZpBannerService;
import com.burst.reptile.modular.web.service.IZpWebinfoService;
import com.burst.reptile.modular.zp.entity.ZpCity;
import com.burst.reptile.modular.zp.entity.ZpCollect;
import com.burst.reptile.modular.zp.entity.ZpColumn;
import com.burst.reptile.modular.zp.entity.ZpLabel;
import com.burst.reptile.modular.zp.entity.ZpNotice;
import com.burst.reptile.modular.zp.entity.ZpQuestion;
import com.burst.reptile.modular.zp.entity.ZpQuestionType;
import com.burst.reptile.modular.zp.entity.ZpRecAuthor;
import com.burst.reptile.modular.zp.entity.ZpResources;
import com.burst.reptile.modular.zp.entity.ZpVote;
import com.burst.reptile.modular.zp.service.IZpCityService;
import com.burst.reptile.modular.zp.service.IZpCollectService;
import com.burst.reptile.modular.zp.service.IZpCommentService;
import com.burst.reptile.modular.zp.service.IZpFormatService;
import com.burst.reptile.modular.zp.service.IZpLabelService;
import com.burst.reptile.modular.zp.service.IZpNoticeService;
import com.burst.reptile.modular.zp.service.IZpQuestionService;
import com.burst.reptile.modular.zp.service.IZpQuestionTypeService;
import com.burst.reptile.modular.zp.service.IZpRecAuthorService;
import com.burst.reptile.modular.zp.service.IZpResourcesService;
import com.burst.reptile.modular.zp.service.IZpServiceItemsService;
import com.burst.reptile.modular.zp.service.IZpVoteService;
import com.burst.reptile.modular.zp.warpper.UserWrapper;
import com.burst.reptile.modular.zp.warpper.ZpRecAuthorWrapper;
import com.burst.reptile.modular.zp.warpper.ZpResourcesWrapper;
import com.hankcs.hanlp.HanLP;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * 赵铺页面控制器
 * @author wujin
 *
 * @date: 2020年6月15日 下午4:39:06
 */
@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZpController extends BaseController{
	
	private final IZpBannerService bannerService;
	
	private final IZpRecAuthorService recAuthorService;
	
	private final IZpLabelService labelService;
	
	private final IZpResourcesService resourcesService;
	
	private final ISysUserService userService;
	
	private final IZpVoteService voteService;
	
	private final IZpCollectService collectService;
	
	private final IZpFormatService formatService;
	
	private final IZpCityService cityService;
	
	private final TokenService tokenService;
	
	private final IZpServiceItemsService serviceItemsService;
	
	private final IZpCommentService commentService;
	
	private final IZpWebinfoService webinfoService;
	
	private final IZpQuestionService questionService;
	
	private final IZpQuestionTypeService questionTypeService;
	
	private final IZpNoticeService noticeService;
	
	/**
	 * 首页
	 * @return
	 */
	@GetMapping({"", "/index"})
	public String index(Model model) {
		model.addAttribute("columnid", 0);
		// 轮播图列表
		List<ZpBanner> banners = bannerService.listShowAll();
		model.addAttribute("banners", banners);
		if(UserAgentUtils.isMobile()) {
			return "H5/index4";
		}
		String city = tokenService.getCitySite();
		
		// 热搜排行
		ZpResources zpResources = new ZpResources();
		zpResources.setCity(city);
		Page<ZpResources> heats = resourcesService.pageListHeats(1, 3, zpResources);
		new ZpResourcesWrapper(heats).wrap();
		model.addAttribute("heats", heats.getRecords());
		// 作者推荐
		List<ZpRecAuthor> authors = recAuthorService.listAll();
		new ZpRecAuthorWrapper(authors).wrap();
		model.addAttribute("authors", authors);
		// 业态标签
		Page<ZpLabel> labels = labelService.pageList(1, 20, new ZpLabel());
		model.addAttribute("labels", labels.getRecords());
		// 推荐文章
		zpResources.setRec("1");
		zpResources.setDraft("0");
		zpResources.setColumnId(1); // 推荐铺友圈的
		Page<ZpResources> list = new Page<>();
		Page<ZpResources> page = new Page<>(1, 10);
		if(SecurityUtils.isLogin()) {
			list = resourcesService.pageList(page, zpResources);
			if(list.getTotal() == 0) {
				zpResources.setRec("0");
				page = resourcesService.pageList(page, zpResources);
			}
		}else {
			list = resourcesService.pageList(page, zpResources);
			if(list.getTotal() == 0) {
				zpResources.setRec("0");
				list = resourcesService.pageList(page, zpResources);
			}
		}
		new ZpResourcesWrapper(list).wrap();
		model.addAttribute("resourcesList", list.getRecords());
		model.addAttribute("hasNext", list.hasNext());
		String citySite = tokenService.getCitySite();
		List<ZpCity> citys = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", citySite));
		if(ToolUtil.isNotEmpty(list)) {
			ZpCity zpCity = citys.get(0);
			String ancestors = zpCity.getAncestors();
			model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + ",-1");
		}
		
		// 平台简介
		String introduction = null;
		ZpWebinfo zpWebinfo = webinfoService.getZpWebinfo("4");
		if(ToolUtil.isNotEmpty(zpWebinfo)) {
			introduction = zpWebinfo.getContent();
		}
		model.addAttribute("introduction", introduction);
		return "index";
	}
	
	/**
	 * 栏目内容
	 * @param id 栏目ID
	 * @param model
	 * @param region 区域
	 * @param format 业态
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@GetMapping("/channel/{id}")
	public String channel(@PathVariable String id, Model model,
			@RequestParam(required = false) String region,
			@RequestParam(required = false) String format,
			@RequestParam(required = false) String server) {
		String title = TITLE;
		// 栏目列表
		List<ZpColumn> columns = (List<ZpColumn>) model.getAttribute("columns");
		for (ZpColumn zpColumn : columns) {
			if(StrUtil.equals(id, zpColumn.getColumnId().toString())) {
				title = zpColumn.getColumnName() + TITLE_SUFFIX;
			}
		}
		model.addAttribute("columnid", NumberUtil.parseInt(id));
		model.addAttribute("title", title);
		// 地区列表
		model.addAttribute("region", cityService.children(tokenService.getCitySite()));
		// 业态列表
		model.addAttribute("formats", formatService.list());
		// 服务类型列表
		model.addAttribute("serverItem", serviceItemsService.list());
		if(UserAgentUtils.isMobile()) {
//			List<ZpBanner> banners = bannerService.listShowAll();
//			model.addAttribute("banners", banners);
			return "H5/channel3";
		}
		
		// 热搜排行
		String city = tokenService.getCitySite();
		ZpResources resources = new ZpResources();
		resources.setCity(city);
		resources.setDraft("0");
		Page<ZpResources> heats = resourcesService.pageListHeats(1, 3, resources);
		new ZpResourcesWrapper(heats).wrap();
		model.addAttribute("heats", heats.getRecords());
		// 作者推荐
		List<ZpRecAuthor> authors = recAuthorService.listAll();
		new ZpRecAuthorWrapper(authors).wrap();
		model.addAttribute("authors", authors);
		// 业态标签
		Page<ZpLabel> labels = labelService.pageList(1, 20, new ZpLabel());
		model.addAttribute("labels", labels.getRecords());
		// 获取文章列表
		Page<ZpResources> pageList = new Page<>();
		Page<ZpResources> page = new Page<>(1, 10);
		boolean hasNext = false;
		if(NumberUtil.isInteger(id)) {
			if(StrUtil.isNotEmpty(format)) {
				resources.setFormatId(NumberUtil.parseInt(format));
			}
			if(StrUtil.isNotEmpty(region)) {
				resources.setCounty(region);
			}
			if(StrUtil.isNotEmpty(server)) {
				resources.setServiceItems(NumberUtil.parseInt(server));
			}
			resources.setColumnId(NumberUtil.parseInt(id));
			pageList = resourcesService.pageList(page, resources);
			hasNext = pageList.hasNext();
		}
		new ZpResourcesWrapper(pageList).wrap();
		model.addAttribute("resourcesList", pageList.getRecords());
		model.addAttribute("hasNext", hasNext);
		model.addAttribute("regionid", region);
		model.addAttribute("formatid", format);
		model.addAttribute("serverid", server);
		return  "page/channel";
	}
	
	/**
	 * 获取文章详情
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/details/{id}")
	@ReadContent
	public String details(@PathVariable String id, Model model) {
		ZpResources resources = resourcesService.getById(id);
		String title = "文章已经不存在了";
		if(ToolUtil.isNotEmpty(resources) && StrUtil.equals(resources.getDraft(), "0")) {
			title = resources.getTitle();
			String tags = resources.getTags();
			String pictureSet = resources.getPictureSet();
			Integer serviceItems = resources.getServiceItems();
			String county = resources.getCounty();
			String city = resources.getCity();
			LocalDateTime createTime = resources.getCreateTime();
			if(StrUtil.isNotEmpty(tags)) {
				resources.setTbs(JSONObject.parseArray(tags, String.class));
			}
			if(StrUtil.isNotEmpty(pictureSet)) {
				resources.setImgs(JSONObject.parseArray(pictureSet, String.class));
			}
			if(ToolUtil.isNotEmpty(createTime)) {
				resources.setTime(DateUtil.timeToFormat(createTime));
			}
			if(ToolUtil.isNotEmpty(serviceItems)) {
				// 服务项目名称
				resources.setServiceItemsName(ConstantFactory.me().getserviceItemsName(serviceItems));
			}
			String countyName = null;
			if(StrUtil.isNotEmpty(city)) {
				countyName = ConstantFactory.me().getAddressName(city);
			}
			if(StrUtil.isNotEmpty(county)) {
				String addressName = ConstantFactory.me().getAddressName(county);
				if(StrUtil.isNotEmpty(countyName) && StrUtil.isNotEmpty(addressName)) {
					countyName = countyName + "-" + addressName;;
				}else if(StrUtil.isNotEmpty(addressName)){
					if(StrUtil.isNotEmpty(addressName)) {
						countyName = "-" + addressName;
					}
				}
				resources.setCountyName(countyName);
			}
			// 作者信息
			Long userId = resources.getUserId();
			SysUser user = userService.getById(userId);
			// 文章和我的关系
			if(SecurityUtils.isLogin()) {
				Long loginUserId = SecurityUtils.getLoginUserId();
				// 是否点赞  是否收藏
				int voteCount = voteService.count(new QueryWrapper<ZpVote>().eq("user_id", loginUserId).eq("article_id", resources.getArticleId()));
				resources.setVote(voteCount > 0);
				int collectCount = collectService.count(new QueryWrapper<ZpCollect>().eq("user_id", loginUserId).eq("article_id", resources.getArticleId()));
				resources.setCollect(collectCount > 0);
				// 是否关注
				if(!userId.equals(loginUserId)) {
					user.setMutual(ConstantFactory.me().mutual(userId, loginUserId));
				}
			}
			resources.setUser(user);
			resources.setCommentNum(commentService.getCommentNum(id));
			// 阅读量格式化
			resources.setReadSizeFormat(NumberUtils.amountConversion(resources.getReadSize()));
			// 点赞量格式化
			resources.setVoteSizeFormat(NumberUtils.amountConversion(resources.getVoteSize()));
			// 收藏量格式化
			resources.setCollectSizeFormat(NumberUtils.amountConversion(resources.getCollectSize()));
			model.addAttribute("resources", resources);
		}else {
			model.addAttribute("resources", null);
		}
		model.addAttribute("title", title);
		return UserAgentUtils.isMobile() ? "H5/details" : "page/details";
	}
	
	/**
	 * 内容预览
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/graphic/preview/{id}")
	public String preview(@PathVariable String id, Model model) {
		ZpResources resources = resourcesService.getById(id);
		String title = "文章已经不存在了";
		Long loginUserId = SecurityUtils.getLoginUserId();
		if(ToolUtil.isNotEmpty(resources) && resources.getUserId().equals(loginUserId)) {
			title = resources.getTitle();
			String tags = resources.getTags();
			String pictureSet = resources.getPictureSet();
			Integer serviceItems = resources.getServiceItems();
			String county = resources.getCounty();
			String city = resources.getCity();
			LocalDateTime updateTime = resources.getUpdateTime();
			if(StrUtil.isNotEmpty(tags)) {
				resources.setTbs(JSONObject.parseArray(tags, String.class));
			}
			if(StrUtil.isNotEmpty(pictureSet)) {
				resources.setImgs(JSONObject.parseArray(pictureSet, String.class));
			}
			if(ToolUtil.isNotEmpty(updateTime)) {
				resources.setTime(DateUtil.timeToFormat(updateTime));
			}
			if(ToolUtil.isNotEmpty(serviceItems)) {
				// 服务项目名称
				resources.setServiceItemsName(ConstantFactory.me().getserviceItemsName(serviceItems));
			}
			String countyName = null;
			if(StrUtil.isNotEmpty(city)) {
				countyName = ConstantFactory.me().getAddressName(city);
			}
			if(StrUtil.isNotEmpty(county)) {
				String addressName = ConstantFactory.me().getAddressName(county);
				if(StrUtil.isNotEmpty(countyName) && StrUtil.isNotEmpty(addressName)) {
					countyName = countyName + "-" + addressName;;
				}else if(StrUtil.isNotEmpty(addressName)){
					if(StrUtil.isNotEmpty(addressName)) {
						countyName = "-" + addressName;
					}
				}
				resources.setCountyName(countyName);
			}
			// 作者信息
			Long userId = resources.getUserId();
			SysUser user = userService.getById(userId);
			resources.setUser(user);
		}
		model.addAttribute("resources", resources);
		model.addAttribute("title", title);
		return "page/preview";
	}
	
	/**
	 * 发布中心
	 * @return
	 */
	@GetMapping("/publish")
	public String publish(Model model) {
		// 获取文章分类	
		Page<ZpLabel> labels = labelService.pageList(1, 15, new ZpLabel());
		model.addAttribute("labels", labels.getRecords());
		model.addAttribute("formats", formatService.list());
		String citySite = tokenService.getCitySite();
		List<ZpCity> list = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", citySite));
		if(ToolUtil.isNotEmpty(list)) {
			ZpCity zpCity = list.get(0);
			String ancestors = zpCity.getAncestors();
			model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + ",-1");
		}
		// 服务项目列表
		model.addAttribute("serviceItems", serviceItemsService.list());
		return "page/publish";
	}
	
	/**
	 * 发布中心
	 * @return
	 */
	@GetMapping("/profile_v2/{type}")
	public String profile_v2(@PathVariable String type, Model model) {
		// 获取文章分类	
		Page<ZpLabel> labels = labelService.pageList(1, 15, new ZpLabel());
		model.addAttribute("labels", labels.getRecords());
		String citySite = null;
		List<ZpCity> list = null;
		switch (type) {
		case "puyouquan": // 铺友圈
			model.addAttribute("tid", 1);
			model.addAttribute("publishName", "铺友圈");
			break;
		case "shangpuzuzhuan": // 商铺租转
			model.addAttribute("tid", 3);
			model.addAttribute("publishName", "商铺租转");
			model.addAttribute("formats", formatService.list());
			citySite = tokenService.getCitySite();
			list = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", citySite));
			if(ToolUtil.isNotEmpty(list)) {
				ZpCity zpCity = list.get(0);
				String ancestors = zpCity.getAncestors();
				model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + ",-1");
			}
			break;
		case "shangpuchushou": // 商铺出售
			model.addAttribute("tid", 4);
			model.addAttribute("publishName", "商铺出售");
			model.addAttribute("formats", formatService.list());
			citySite = tokenService.getCitySite();
			list = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", citySite));
			if(ToolUtil.isNotEmpty(list)) {
				ZpCity zpCity = list.get(0);
				String ancestors = zpCity.getAncestors();
				model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + ",-1");
			}
			break;
		case "xinpuzushou": // 新铺租售
			model.addAttribute("tid", 5);
			model.addAttribute("publishName", "新铺租售");
			model.addAttribute("formats", formatService.list());
			citySite = tokenService.getCitySite();
			list = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", citySite));
			if(ToolUtil.isNotEmpty(list)) {
				ZpCity zpCity = list.get(0);
				String ancestors = zpCity.getAncestors();
				model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + ",-1");
			}
			break;
		case "shanghuhuodong": // 商户活动
			model.addAttribute("tid", 7);
			model.addAttribute("publishName", "商户活动");
			model.addAttribute("formats", formatService.list());
			citySite = tokenService.getCitySite();
			list = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", citySite));
			if(ToolUtil.isNotEmpty(list)) {
				ZpCity zpCity = list.get(0);
				String ancestors = zpCity.getAncestors();
				model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + ",-1");
			}
			break;
		case "shanghufuwu": // 商户服务
			model.addAttribute("tid", 6);
			model.addAttribute("publishName", "商户服务");
			model.addAttribute("formats", formatService.list());
			citySite = tokenService.getCitySite();
			list = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", citySite));
			if(ToolUtil.isNotEmpty(list)) {
				ZpCity zpCity = list.get(0);
				String ancestors = zpCity.getAncestors();
				model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + ",-1");
			}
			// 服务项目列表
			model.addAttribute("serviceItems", serviceItemsService.list());
			break;
		default: // 铺友圈
			model.addAttribute("tid", 1);
			model.addAttribute("publishName", "铺友圈");
			break;
		}
		return "page/publish2";
	}
	
	@GetMapping("/profile2")
	public String profile2() {
		return "page/profile/index";
	}
	
	/**
	 * 搜索
	 * @param keyword
	 * @return
	 */
	@GetMapping("/search")
	public String search(@RequestParam(required = false) String keyword, Model model) {
		// 热搜排行
		String city = tokenService.getCitySite();
		ZpResources zpResources = new ZpResources();
		zpResources.setCity(city);
		Page<ZpResources> heats = resourcesService.pageListHeats(1, 3, zpResources);
		new ZpResourcesWrapper(heats).wrap();
		model.addAttribute("heats", heats.getRecords());
		// 作者推荐
		List<ZpRecAuthor> authors = recAuthorService.listAll();
		new ZpRecAuthorWrapper(authors).wrap();
		model.addAttribute("authors", authors);
		// 业态标签
		Page<ZpLabel> labels = labelService.pageList(1, 20, new ZpLabel());
		model.addAttribute("labels", labels.getRecords());
		Page<ZpResources> pagelist = new Page<>();
		List<ZpResources> records = new ArrayList<>();
		if(StrUtil.isNotEmpty(keyword)) {
			List<String> ik = HanLP.extractKeyword(keyword, 3);
			pagelist = resourcesService.search(1, 10, keyword, ik);
			new ZpResourcesWrapper(pagelist).wrap();
			records = pagelist.getRecords();
			if(ToolUtil.isNotEmpty(records)) {
				records.forEach(i -> {
					String title = i.getTitle();
					String summary = i.getSummary();
					title = StrUtil.replace(title, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					summary = StrUtil.replace(summary, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					if(ToolUtil.isNotEmpty(ik)) {
						for (String str : ik) {
							title = StrUtil.replace(title, str, "<span style='color:#ff4200;'>" + str + "</span>");
							summary = StrUtil.replace(summary, str, "<span style='color:#ff4200;'>" + str + "</span>");
							if(str.matches(".*[a-zA-z].*")) {
								String swapCase = StrUtil.swapCase(str);
								title = StrUtil.replace(title, swapCase, "<span style='color:#ff4200;'>" + swapCase + "</span>");
								summary = StrUtil.replace(summary, swapCase, "<span style='color:#ff4200;'>" + swapCase + "</span>");
							}
						}
					}
					i.setTitle(title);
					i.setSummary(summary);
				});
			}
		}
		model.addAttribute("resourcesList", records);
		model.addAttribute("keyword", keyword);
		model.addAttribute("hasNext", pagelist.hasNext());
		return "page/search";
	}
	
	@GetMapping("/h5search")
	public String search() {
		return "H5/search";
	}
	
	/**
	 * 搜索作者
	 * @param keyword
	 * @return
	 */
	@GetMapping("/shearauthor")
	public String shearauthor(@RequestParam(required = false) String keyword, Model model) {
		// 热搜排行
		String city = tokenService.getCitySite();
		ZpResources zpResources = new ZpResources();
		zpResources.setCity(city);
		Page<ZpResources> heats = resourcesService.pageListHeats(1, 3, zpResources);
		new ZpResourcesWrapper(heats).wrap();
		model.addAttribute("heats", heats.getRecords());
		// 作者推荐
		List<ZpRecAuthor> authors = recAuthorService.listAll();
		new ZpRecAuthorWrapper(authors).wrap();
		model.addAttribute("authors", authors);
		// 业态标签
		Page<ZpLabel> labels = labelService.pageList(1, 20, new ZpLabel());
		model.addAttribute("labels", labels.getRecords());
		
		Page<SysUser> pagelist = new Page<>();
		List<SysUser> records = new ArrayList<>();
		if(StrUtil.isNotEmpty(keyword)) {
			List<String> ik = HanLP.extractKeyword(keyword, 3);
			pagelist = userService.search(1, 10, keyword, ik);
			new UserWrapper(pagelist).wrap();
			records = pagelist.getRecords();
			if(ToolUtil.isNotEmpty(records)) {
				records.forEach(i -> {
					String nickName = i.getNickName();
					nickName = StrUtil.replace(nickName, keyword, "<span style='color:#ff4200;'>" + keyword + "</span>");
					if(ToolUtil.isNotEmpty(ik)) {
						for (String str : ik) {
							nickName = StrUtil.replace(nickName, str, "<span style='color:#ff4200;'>" + str + "</span>");
							if(str.matches(".*[a-zA-z].*")) {
								String swapCase = StrUtil.swapCase(str);
								nickName = StrUtil.replace(nickName, swapCase, "<span style='color:#ff4200;'>" + swapCase + "</span>");
							}
						}
					}
					i.setNickName(nickName);
				});
			}
		}
		model.addAttribute("authorlist", records);
		model.addAttribute("keyword", keyword);
		model.addAttribute("hasNext", pagelist.hasNext());
		return "page/searchAutor";
	}
	
	/**
	 * 隐私政策
	 * @return
	 */
	@GetMapping("/privacy")
	public String privacy(Model model) {
		model.addAttribute("privacy", webinfoService.getZpWebinfo("1"));
		return UserAgentUtils.isMobile() ? "H5/privacy" : "privacy";
	}
	
	/**
	 * 隐私声明
	 * @return
	 */
	@GetMapping("/privacyinfo")
	public String privacyinfo(Model model) {
		model.addAttribute("privacy", webinfoService.getZpWebinfo("1"));
		return "page/webinfo/privacy";
	}
	
	/**
	 * 关于我们
	 * @return
	 */
	@GetMapping("/aboutshuaixiaopu")
	public String aboutshuaixiaopu(Model model) {
		model.addAttribute("privacy", webinfoService.getZpWebinfo("2"));
		return "page/webinfo/aboutshuaixiaopu";
	}
	
	/**
	 * 联系我们
	 * @return
	 */
	@GetMapping("/contactus")
	public String contactus(Model model) {
		model.addAttribute("privacy", webinfoService.getZpWebinfo("3"));
		return "page/webinfo/contactus";
	}
	
	/**
	 * 我的个人中心
	 * @return
	 */
	@GetMapping("/u/profile")
	public String profile(Model model) {
		Long userId = SecurityUtils.getLoginUserId();
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return UserAgentUtils.isMobile() ? "H5/profile" : "page/user/information";
	}
	
	/**
	 * 我的点赞列表
	 * @return
	 */
	@GetMapping("/u/vote")
	public String vote(Model model) {
		Long userId = SecurityUtils.getLoginUserId();
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/user/vote";
	}
	
	/**
	 * 我的收藏列表
	 * @return
	 */
	@GetMapping("/u/collect")
	public String collect(Model model) {
		Long userId = SecurityUtils.getLoginUserId();
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/user/collect";
	}
	
	/**
	 * 我的关注
	 * @return
	 */
	@GetMapping("/u/follow")
	public String follow(Model model) {
		Long userId = SecurityUtils.getLoginUserId();
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/user/follow";
	}
	
	/**
	 * 我的粉丝
	 * @return
	 */
	@GetMapping("/u/fans")
	public String fans(Model model) {
		Long userId = SecurityUtils.getLoginUserId();
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/user/fans";
	}
	
	
	/**
	 * 用户个人中心
	 * @return
	 */
	@GetMapping("/t/{userId}")
	public String profile(@PathVariable Long userId, Model model) {
		boolean follow = false;
		SysUser user = userService.getById(userId);
		if(ToolUtil.isEmpty(user)) {
			return "forward:/404";
		}
		if(SecurityUtils.isLogin()) {
			Long loginuserId = SecurityUtils.getLoginUserId();
			if(userId.equals(loginuserId)) {
				return "forward:/u/profile";
			}
			follow = ConstantFactory.me().mutual(userId, loginuserId);
		}
		
		model.addAttribute("authuser", user);
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		model.addAttribute("follow", follow);
		return "page/tuser/information";
	}
	
	/**
	 * 用户点赞列表
	 * @return
	 */
	@GetMapping("/t/vote/{userId}")
	public String vote(@PathVariable Long userId, Model model) {
		if(SecurityUtils.isLogin()) {
			// 分页获取我的日记列表
			Long loginuserId = SecurityUtils.getLoginUserId();
			if(userId.equals(loginuserId)) {
				return "redirect:/u/vote";
			}
		}
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/tuser/vote";
	}
	
	/**
	 * 用户收藏列表
	 * @return
	 */
	@GetMapping("/t/collect/{userId}")
	public String collect(@PathVariable Long userId, Model model) {
		if(SecurityUtils.isLogin()) {
			// 分页获取我的日记列表
			Long loginuserId = SecurityUtils.getLoginUserId();
			if(userId.equals(loginuserId)) {
				return "redirect:/u/collect";
			}
		}
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/tuser/collect";
	}
	
	/**
	 * 用户关注列表
	 * @return
	 */
	@GetMapping("/t/follow/{userId}")
	public String follow(@PathVariable Long userId, Model model) {
		if(SecurityUtils.isLogin()) {
			// 分页获取我的日记列表
			Long loginuserId = SecurityUtils.getLoginUserId();
			if(userId.equals(loginuserId)) {
				return "redirect:/u/follow";
			}
		}
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/tuser/follow";
	}
	
	/**
	 * 用户关注列表
	 * @return
	 */
	@GetMapping("/t/fans/{userId}")
	public String fans(@PathVariable Long userId, Model model) {
		if(SecurityUtils.isLogin()) {
			// 分页获取我的日记列表
			Long loginuserId = SecurityUtils.getLoginUserId();
			if(userId.equals(loginuserId)) {
				return "redirect:/u/fans";
			}
		}
		model.addAttribute("authuser", userService.getById(userId));
		// 发布数量
		model.addAttribute("releaseNum", ConstantFactory.me().getReleaseVolume(userId));
		// 点赞数量
		model.addAttribute("giveNum", ConstantFactory.me().getLikes(userId));
		// 收藏数量
		model.addAttribute("collectNum", ConstantFactory.me().getCollects(userId));
		// 关注数量
		model.addAttribute("followNum", ConstantFactory.me().getAttention(userId));
		// 粉丝数量
		model.addAttribute("fansNum", ConstantFactory.me().getFans(userId));
		return "page/tuser/fans";
	}
	
	/**
	 * 获取城市
	 * @return
	 */
	@GetMapping("/city")
	public String city(Model model) {
		Map<String, List<ZpCity>> map = new HashMap<>();
		map.put("A", new ArrayList<>());
		map.put("B", new ArrayList<>());
		map.put("C", new ArrayList<>());
		map.put("D", new ArrayList<>());
		map.put("E", new ArrayList<>());
		map.put("F", new ArrayList<>());
		map.put("G", new ArrayList<>());
		map.put("H", new ArrayList<>());
		map.put("I", new ArrayList<>());
		map.put("J", new ArrayList<>());
		map.put("K", new ArrayList<>());
		map.put("L", new ArrayList<>());
		map.put("M", new ArrayList<>());
		map.put("N", new ArrayList<>());
		map.put("O", new ArrayList<>());
		map.put("P", new ArrayList<>());
		map.put("Q", new ArrayList<>());
		map.put("R", new ArrayList<>());
		map.put("S", new ArrayList<>());
		map.put("T", new ArrayList<>());
		map.put("U", new ArrayList<>());
		map.put("V", new ArrayList<>());
		map.put("W", new ArrayList<>());
		map.put("X", new ArrayList<>());
		map.put("Y", new ArrayList<>());
		map.put("Z", new ArrayList<>());
		// 获取一级省会城市
		List<ZpCity> list = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", 0).eq("disabled", "0"));
	
		boolean mobile = UserAgentUtils.isMobile();
		if(mobile) {
			for (ZpCity zpCity : list) {
				List<ZpCity> children = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", zpCity.getAid()).eq("disabled", "0").orderByAsc("first_char"));
				if(ToolUtil.isNotEmpty(children)) {
					for (ZpCity chi : children) {
						String firstChar = chi.getFirstChar();
						List<ZpCity> cs = map.get(firstChar);
						cs.add(chi);
					}
				}
			}
		}else {
			for (ZpCity zpCity : list) {
				List<ZpCity> children = cityService.list(new QueryWrapper<ZpCity>().eq("parent_id", zpCity.getAid()).eq("disabled", "0").orderByAsc("first_char"));
				zpCity.setChildren(children);
				List<ZpCity> cs = map.get(zpCity.getFirstChar());
				cs.add(zpCity);
			}
		}
		Map<String, List<ZpCity>> result = map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
		model.addAttribute("citys", result);
		return mobile ? "H5/city" : "city";
	}
	
	/**
	 * 资源管理
	 * @param model
	 * @return
	 */
	@GetMapping("/res/manage/list")
	public String resManage(Model model) {
		model.addAttribute("formats", formatService.list());
		model.addAttribute("serviceItems", serviceItemsService.list());
		return "page/manage/articleManage";
	}
	
	/**
	 * 资源管理
	 * @param model
	 * @return
	 */
	@GetMapping("/res/manage2/list")
	public String resManage2(Model model) {
		model.addAttribute("formats", formatService.list());
		model.addAttribute("serviceItems", serviceItemsService.list());
		return "page/manage/articleManage2";
	}
	
	/**
	 * 编辑资源
	 * @param model
	 * @return
	 */
	@GetMapping("/res/manage/edit/{id}")
	public String edit(@PathVariable String id, Model model) {
		ZpResources resources = resourcesService.getById(id);
		if(ToolUtil.isNotEmpty(resources)) {
			String tags = resources.getTags();
			if(StrUtil.isNotEmpty(tags)) {
				List<String> parseArray = JSONObject.parseArray(tags, String.class);
				resources.setTags(CollUtil.join(parseArray, ","));
			}
			String county = resources.getCounty();
			ZpCity byId = cityService.getById(county);
			if(ToolUtil.isNotEmpty(byId)) {
				String ancestors = byId.getAncestors();
				model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + "," + county);
			}
			// 获取文章分类	
			Page<ZpLabel> labels = labelService.pageList(1, 15, new ZpLabel());
			model.addAttribute("labels", labels.getRecords());
			model.addAttribute("formats", formatService.list());
				
			// 服务项目列表
			model.addAttribute("serviceItems", serviceItemsService.list());
		}
		model.addAttribute("resources", resources);
		return "page/manage/edit";
	}
	
	/**
	 * 编辑资源
	 * @param model
	 * @return
	 */
	@GetMapping("/res/manage/edit2/{id}")
	public String edit2(@PathVariable String id, Model model) {
		ZpResources resources = resourcesService.getById(id);
		if(ToolUtil.isNotEmpty(resources)) {
			String tags = resources.getTags();
			if(StrUtil.isNotEmpty(tags)) {
				List<String> parseArray = JSONObject.parseArray(tags, String.class);
				resources.setTags(CollUtil.join(parseArray, ","));
			}
			String county = resources.getCounty();
			ZpCity byId = cityService.getById(county);
			if(ToolUtil.isNotEmpty(byId)) {
				String ancestors = byId.getAncestors();
				model.addAttribute("citycode", ancestors.substring(2, ancestors.length()) + "," + county);
			}
			// 获取文章分类	
			Page<ZpLabel> labels = labelService.pageList(1, 15, new ZpLabel());
			model.addAttribute("labels", labels.getRecords());
			
			Integer columnId = resources.getColumnId();
			model.addAttribute("tid", columnId);
			switch (columnId) {
			case 1:
				model.addAttribute("publishName", "铺友圈");
				break;
			case 3:
				model.addAttribute("publishName", "商铺租转");
				model.addAttribute("formats", formatService.list());
				break;
			case 4:
				model.addAttribute("publishName", "商铺出售");
				model.addAttribute("formats", formatService.list());
				break;
			case 5:
				model.addAttribute("publishName", "新铺租售");
				model.addAttribute("formats", formatService.list());
				break;
			case 6:
				model.addAttribute("publishName", "商户服务");
				model.addAttribute("formats", formatService.list());
				// 服务项目列表
				model.addAttribute("serviceItems", serviceItemsService.list());
				break;
			case 7:
				model.addAttribute("publishName", "商户活动");
				model.addAttribute("formats", formatService.list());
				break;
			default:
				break;
			}
		}
		model.addAttribute("resources", resources);
		return "page/manage/edit2";
	}
	
	/**
	 * 问问专家
	 * @return
	 */
	@GetMapping("/ask")
	public String buyinghouse(Model model) {
		model.addAttribute("columnid", -1);
		// 获取咨询类型
		List<ZpQuestionType> list = questionTypeService.list();
		String citySite = tokenService.getCitySite();
		if(ToolUtil.isNotEmpty(list)) {
			list.forEach(i -> {
				int count = questionService.count(new QueryWrapper<ZpQuestion>().eq("question_type", i.getQid()).eq("city", citySite));
				i.setNum(count);
			});
		}
		model.addAttribute("questionType", list);
		int count2 = questionService.count(new QueryWrapper<ZpQuestion>().eq("qu_status", "1").eq("city", citySite));
		model.addAttribute("anum", count2);
		return UserAgentUtils.isMobile() ? "H5/buyinghouse" : "page/buyinghouse";
	}
	
	/**
	 * 问问专家
	 * @return
	 */
	@GetMapping("/ask/{id}")
	public String busdis(Model model) {
		return "H5/budis";
	}
	
	/**
	 * 行业圈友
	 * @return
	 */
	@GetMapping("/circlefriend")
	public String circlefriend(@RequestParam(required = false) String id, Model model) {
		// 业态列表
		model.addAttribute("selectlist", formatService.list());
		model.addAttribute("fid", id);
		return "page/industryFriend";
	}
	
	/**
	 * 个人信息
	 * @return
	 */
	@GetMapping("/u/usersettings")
	public String usersettings(Model model) {
		// 业态列表
		model.addAttribute("formats", formatService.list());
		return "page/user/userInfo";
	}
	
	/**
	 * 公告
	 * @return
	 */
	@GetMapping("/u/notice")
	public String notice(Model model) {
		// 业态列表
		return "page/msg/notice";
	}
	
	/**
	 * 通知
	 * @return
	 */
	@GetMapping("/u/msg")
	public String msg(Model model) {
		return "page/user/userInfo";
	}
	
	/**
	 * 公告详情
	 * @return
	 */
	@GetMapping("/u/notice/{id}")
	public String notice(@PathVariable String id, Model model) {
		ZpNotice byId = noticeService.getById(id);
		if(byId != null) {
			String noticeStatus = byId.getNoticeStatus();
			if(StrUtil.equals(noticeStatus, "0")) {
				model.addAttribute("notice", byId);
				byId.setReadSize(byId.getReadSize() + 1);
				noticeService.updateById(byId);
			}else {
				model.addAttribute("notice", null);
			}
		}else {
			model.addAttribute("notice", null);
		}
		return "page/msg/info";
	}
	
	/**
	 * 意见反馈
	 * @return
	 */
	@GetMapping("/help")
	public String help() {
		return "page/help";
	}
	
	/**
	 * h5评论
	 * @param article 文章id
	 * @param model
	 * @return
	 */
	@GetMapping("/h5/comment")
	public String comment(@RequestParam(value="id",required=false) String id,
			Model model) {
		model.addAttribute("article", id);
		return "H5/comment";
	}
	
	/**
	 * H5回复评论
	 * @param id 文章ID
	 * @param pcid 回复评论ID或回复回复的ID
	 * @param acid 所属评论ID
	 * @param touserId 回复用户ID
	 * @param name 回复用户的昵称
	 * @param model
	 * @return
	 */
	@GetMapping("/h5/reply")
	public String reply(@RequestParam(value="id",required=false) String id,
			@RequestParam(value="pcid",required=false) String pcid,
			@RequestParam(value="acid",required=false) String acid,
			@RequestParam(value="touserId",required=false) String touserId,
			@RequestParam(value="name",required=false) String name,
			Model model) {
		model.addAttribute("article", id);
		model.addAttribute("pcid", pcid);
		model.addAttribute("acid", acid);
		model.addAttribute("touserId", touserId);
		model.addAttribute("name", name);
		return "H5/reply";
	}
	
}
